package com.zl.smartmall.library.listener;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.zl.smartmall.library.util.CrashHandler;

/**
 * 获取微信AccessToken数据监听器
 * @author 陈希然
 *
 */
public abstract class WechatAccessTokenListener extends BaseListener {

	private static final String TAG = WechatAccessTokenListener.class.getSimpleName();
	@Override
	public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
		try {
			CrashHandler.d(TAG, response.toString());
			if(response.has("errcode")) {
				onResponseFailed();
				
			}else {
				int expiresIn = response.getInt("expires_in");
				String accessToken = response.getString("access_token"); 
				String refreshToken = response.getString("refresh_token");
				String openId = response.getString("openid");
				String scope = response.getString("scope");

				onResponseSuccess(expiresIn, accessToken, openId, refreshToken, scope);
			}
			
		} catch (JSONException e) {
			CrashHandler.e(e);
			onResponseFailed();
		}
	}
	
	@Override
	public void onFailure(int statusCode, Header[] headers,
			Throwable throwable, JSONObject errorResponse) {
		// TODO Auto-generated method stub
		CrashHandler.e(throwable);
		onResponseFailed();
	}
	
	@Override
	public void onNoMoreData() {}
	
	@Override
	public void onOffline() {}

	/**
	 * 微信AccessToken获取成功
	 * @param expiresIn access_token接口调用凭证超时时间，单位（秒）
	 * @param accessToken 接口调用凭证
	 * @param openId 授权用户唯一标识
	 * @param refreshToken 用户刷新access_token
	 * @param scope 用户授权的作用域，使用逗号（,）分隔
	 */
	public abstract void onResponseSuccess(int expiresIn, String accessToken, String openId, String refreshToken, String scope);
}
